﻿#include "detector.h"
#include <QStringList>
#include <QDebug>
#include <QImage>
#include <QDir>


detector::detector(QObject *parent) : QThread(parent)
{
    capture = new cv::VideoCapture();
    yolov8 = new YOLOV8();
    onnxFile = yolov8->NetPath[0];
    if (! yolov8->Initialization(yolov8->NetPath[0])){
        QString model_info(QStringLiteral("初始化失败！"));
        emit send_init_info(model_info);
        return;
    }
    m_init = true;
    QString init_info(QStringLiteral("初始化成功 onnxFile=%1 模型成功！").arg(onnxFile));
    emit send_init_info(init_info);
}


detector::~detector()
{
    capture->release();
    delete capture;
    delete yolov8;
}


void detector::run()
{
    while (!isInterruptionRequested() && cv::waitKey(30) != 27) {
        capture->read(frame);
        if (frame.empty()) continue;
        auto start = std::chrono::steady_clock::now();
        yolov8->detect(frame);
        yolov8->draw_objects(frame);
        auto end = std::chrono::steady_clock::now();
        std::chrono::duration<double, std::milli> elapsed = end - start;
        QString detect_info(QString("cost_time: %1 ms").arg(elapsed.count()));
        emit send_detect_info(detect_info);
        cv::cvtColor(frame, frame, cv::COLOR_BGR2RGB);
        QImage rawImage = QImage((uchar*)(frame.data),frame.cols,frame.rows,frame.step,QImage::Format_RGB888);
        emit send_display_info(rawImage);
    }
}



void detector::recv_videofile(QString filename)
{
    videoName = filename;
    proprecessing_video();
}



void detector::proprecessing_video()
{
    capture->open(videoName.toLatin1().data());
    if (!capture->isOpened()){
        QString video_info(QStringLiteral("打开 MP4 失败（文件不存在或者文件路径有中文）!"));
        emit send_video_info(video_info);
        emit send_ready(false);
        return;
    }

    long totalFrame = capture->get(cv::CAP_PROP_FRAME_COUNT);
    int width = capture->get(cv::CAP_PROP_FRAME_WIDTH);
    int height = capture->get(cv::CAP_PROP_FRAME_HEIGHT);
    capture->set(cv::CAP_PROP_POS_FRAMES, 0);
    double rate = capture->get(cv::CAP_PROP_FPS);
    QString video_info(QStringLiteral("整个视频共有帧数=%1, \t图像宽=%2 \t图像高=%3 \t帧率=%4")
                       .arg(totalFrame).arg(width).arg(height).arg(rate));

    emit send_video_info(video_info);
    if(m_init)
        emit send_ready(true);
}


void detector::recv_comboBox_arg(const QString arg1)
{
    if (arg1.contains("速度"))
        onnxFile = yolov8->NetPath[0];
    else
        onnxFile = yolov8->NetPath[1];
    yolov8->Initialization(onnxFile.toLatin1().data());
    QString comboBox_info(QStringLiteral("正在使用模型类别：%1").arg(arg1));
    emit send_comboBox_info(comboBox_info);
}



